package com.lianzai.ticket.controller;

import com.lianzai.car.domain.CarLogDO;
import com.lianzai.common.annotation.NoLoginAuthRequired;
import com.lianzai.common.controller.BaseController;
import com.lianzai.common.utils.PageUtils;
import com.lianzai.common.utils.Query;
import com.lianzai.common.utils.R;
import com.lianzai.ticket.model.*;
import com.lianzai.ticket.service.GiftService;
import com.lianzai.ticket.service.TicketService;
import org.apache.commons.collections.map.HashedMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;


@Controller
@RequestMapping("/ticket")
public class TicketController extends BaseController {

    @Autowired
    TicketService ticketService;
    @Autowired
    GiftService giftService;

    @GetMapping()
    String ticket(){
        return "ticket/list";
    }

    @ResponseBody
    @GetMapping("/list")
    public PageUtils list(@RequestParam Map<String, Object> params){
        //查询列表数据
        Query query = new Query(params);
        List<Ticket> carInfoList = ticketService.list(query);
        int total = ticketService.count(query);
        PageUtils pageUtils = new PageUtils(carInfoList, total);
        return pageUtils;
    }

    @ResponseBody
    @GetMapping("/listByCommunityId")
    public PageUtils listByCommunityId(@RequestParam Map<String, Object> params){
        //查询列表数据
        Query query = new Query(params);
        List<Ticket> carInfoList = ticketService.list(query);
        //查询小区与停车券关联表
        for(Ticket ticket:carInfoList){
            Map paramsMap = new HashedMap();
            paramsMap.put("communityId",String.valueOf(params.get("communityId")));
            paramsMap.put("ticketId",ticket.getId());
            List relList = ticketService.listRel(paramsMap);
            if(relList != null && relList.size() > 0){
                ticket.setBindStatus("1");
            }else{
                ticket.setBindStatus("0");
            }
        }
        int total = ticketService.count(query);
        PageUtils pageUtils = new PageUtils(carInfoList, total);
        return pageUtils;
    }

    @PostMapping( "/remove")
    @ResponseBody
    public R remove( Long id){
        //校验是否有有商户在用 如果有则不能删除
        Map params = new HashedMap();
        params.put("ticketId",id);
        List<Map> ticketShopList = ticketService.queryTicektShopUsedList(params);
        if(ticketShopList != null && ticketShopList.size() > 0){
            return R.error(110,"删除失败，原因：有小区关联了此停车券");
        }
        if(ticketService.remove(id)>0){
            return R.ok();
        }
        return R.error();
    }

    @GetMapping("/add")
    String add(){
        return "ticket/add";
    }

    @GetMapping("/giftadd/{buyNums}")
    String giftadd(@PathVariable("buyNums") String buyNums,Model model){
        model.addAttribute("buyNums", buyNums);
        return "ticket/gift/add";
    }

    @GetMapping("/edit/{id}")
    String edit(@PathVariable("id") Long id,Model model){
        Ticket ticket = ticketService.get(id);
        List<Gift> giftList = giftService.queryGiftList(ticket.getId());
        model.addAttribute("ticket", ticket);
        model.addAttribute("giftList", giftList);
        model.addAttribute("giftCnt", giftList.size());
        return "ticket/edit";
    }

    @ResponseBody
    @PostMapping("/save")
    public R save( Ticket ticket){
        ticket.setCreateBy(getUserId()+"");
        if(ticketService.save(ticket)>0){
            return R.ok();
        }
        return R.error();
    }
    @ResponseBody
    @PostMapping("/check")
    public R check( Ticket ticket){
        List<Ticket> retList = ticketService.check(ticket.getTicketName());
        if(ticket.getId() == null){//证明是新增时的校验
            if(retList == null || retList.size()==0){
                return R.ok();
            }
        }else{
            if(retList == null || retList.size()==0){
                return R.ok();
            }else{
                if(retList.size() == 1){
                    if(retList.get(0).getId() == ticket.getId()){//如果是自己没有变
                        return R.ok();
                    }
                }
            }
        }
        return R.error();
    }

    @ResponseBody
    @RequestMapping("/update")
    public R update( Ticket ticket){
        ticket.setUpdateBy(getUserId()+"");
        if(ticketService.update(ticket)>0){
            return R.ok();
        }
        return R.error();
    }

    /**
     * 绑定停车券
     */
    @PostMapping( "/bind")
    @ResponseBody
    public R bind( Long communityId,Long ticketId,int type){
        if(ticketService.bind(communityId,ticketId,type)>0){
            return R.ok();
        }
        return R.error();
    }

    @NoLoginAuthRequired
    @ResponseBody
    @GetMapping("/thirdParty/getByWXId")
    public R getTicketByWXId(@RequestParam String openId)
    {
        Ticket ticket = ticketService.getTicketByWXId(openId);

        if (ticket != null)
        {
            R r = new R();
            r.put("ticket", ticket);
            return r;
        }
        else
        {
            return R.error("获取停车券失败");
        }
    }

    @NoLoginAuthRequired
    @ResponseBody
    @GetMapping("/thirdParty/getOverviewByUserId")
    public R getOverviewByUserId(@RequestParam String userId)
    {
        int id;
        try
        {
            id = Integer.parseInt(userId);
        }
        catch (Exception e)
        {
            return R.error("用户id错误");
        }
        MerchantTicketDO merchantTicketDO = ticketService.getTicketOverview(id);

        if (merchantTicketDO != null)
        {
            R r = new R();
            r.put("overview", merchantTicketDO);
            return r;
        }
        else
        {
            return R.error("获取商户停车券信息失败");
        }
    }

    @NoLoginAuthRequired
    @ResponseBody
    @GetMapping("/thirdParty/getOrderListByUserId")
    public PageUtils getOrderListByUserId(@RequestParam Map<String, Object> params)
    {
        int userId;
        try
        {
            userId = Integer.parseInt(params.get("userId").toString());
        }
        catch (Exception e)
        {
            return new PageUtils(null, 0);
        }

        //将数字类型的参数转为数字
        params.put("offset", Integer.parseInt(params.get("offset").toString()));
        params.put("limit", Integer.parseInt(params.get("limit").toString()));
        params.put("userId", userId);

        List<Map<String, Object>> orderList = ticketService.getTicketOrderList(params);
        int total = ticketService.countTicketOrder(userId);


        if (orderList != null && orderList.size() > 0)
        {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            for (Map<String, Object> map : orderList)
            {
                Timestamp payTime = (Timestamp) map.get("pay_time");
                if (payTime == null)
                {
                    continue;
                }
                map.put("pay_time", sdf.format(new Date(payTime.getTime())));
            }
        }
        PageUtils pageUtils = new PageUtils(orderList, total);
        return pageUtils;
    }

    @NoLoginAuthRequired
    @ResponseBody
    @GetMapping("/thirdParty/getUseListByUserId")
    public PageUtils getUseListByUserId(@RequestParam Map<String, Object> params)
    {
        int userId;
        try
        {
            userId = Integer.parseInt(params.get("userId").toString());
        }
        catch (Exception e)
        {
            return new PageUtils(null, 0);
        }

        //将数字类型的参数转为数字
        params.put("offset", Integer.parseInt(params.get("offset").toString()));
        params.put("limit", Integer.parseInt(params.get("limit").toString()));
        params.put("userId", userId);

        List<TicketUseInfoDO> ticketUseList = ticketService.getTicketUseList(params);
        int total = ticketService.countTicketUse(params);


        PageUtils pageUtils = new PageUtils(ticketUseList, total);
        return pageUtils;
    }
}
